package com.lamp.uploadimage;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

public class UploadImage {

	private String json;
	private final Bitmap bitmap;
	private Activity _currentActivity;
	
	public UploadImage (Bitmap bitmap , Activity _currentActivity){
		this.bitmap = bitmap;
		this._currentActivity = _currentActivity;
	}
	
	public void uploadImage(String url){
		BitmapUploadTask task = new BitmapUploadTask(url);
		task.execute();
	}
	
	public void uploadBitmap(Bitmap bitmap , String url){
		
		
		HttpClient client = new DefaultHttpClient();
		
        HttpPost httpPost = new HttpPost(url); 
		
		MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);    
  
  
        Bitmap bmpCompressed = Bitmap.createScaledBitmap(bitmap, 150, 150, true);  
        ByteArrayOutputStream bos = new ByteArrayOutputStream();  
  
        bmpCompressed.compress(CompressFormat.JPEG, 100, bos);  
        byte[] data = bos.toByteArray();  
  
  
        
  
        entity.addPart("fpath", new ByteArrayBody(data, "myavatar.jpg"));  
       
        httpPost.setEntity(entity); 
		
		
		try {
			HttpResponse response = client.execute(httpPost);
			final int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				Log.w("ImageDownloader", "Error " + statusCode
						+ " while retrieving bitmap from " + url);
			}

				BufferedReader in ;
				InputStreamReader inputStream = null;
				try {
					inputStream = new InputStreamReader(response.getEntity().getContent() , HTTP.UTF_8);
					
					in = new BufferedReader(inputStream);
					
					String line = "";
					json = "";
					String buffer = "";
					while ((line = in.readLine()) != null) {

						json += line;
					}
					
					
				} finally {
					if (inputStream != null) {
						inputStream.close();
					}
					entity.consumeContent();
				}
			
		} catch (IOException e) {
			httpPost.abort();
			Log.w("ImageDownloader", "no connection" + url, e);
		} catch (IllegalStateException e) {
			httpPost.abort();
			Log.w("ImageDownloader", "wrong URL: " + url);
		} catch (Exception e) {
			httpPost.abort();
			Log.w("ImageDownloader", "" + url, e);
		}
		
	}
	
	static class FlushedInputStream extends FilterInputStream {
		public FlushedInputStream(InputStream inputStream) {
			super(inputStream);
		}

		@Override
		public long skip(long n) throws IOException {
			long totalBytesSkipped = 0L;
			while (totalBytesSkipped < n) {
				long bytesSkipped = in.skip(n - totalBytesSkipped);
				if (bytesSkipped == 0L) {
					int b = read();
					if (b < 0) {
						break;
					} else {
						bytesSkipped = 1;
					}
				}
				totalBytesSkipped += bytesSkipped;
			}
			return totalBytesSkipped;
		}
	}
	
	
	class BitmapUploadTask extends AsyncTask<Void, String, String>{

		private String url;
		
		public BitmapUploadTask(String url){
			this.url = url;
		}
		@Override
		protected String doInBackground(Void... arg0) {
			
			if (bitmap != null){
					uploadBitmap(bitmap , url);
				return json;
			}
			else return "NO" ;
			// TODO Auto-generated method stub
			
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			
			Log.d("UPLOADIMAGE", result);
			
			if (result != "NO"){
				try {
					JSONObject status = new JSONObject(result);
					
					if (status.getInt("StatusCode") == 0)
					{
						AlertDialog.Builder builder = new AlertDialog.Builder(_currentActivity);
						builder.setMessage("hello from ");
						builder.setPositiveButton("Cool", null);
						builder.show();
					}
					
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		}
		
		
	}
}
